package com.duojuhe.common.utils.timestamp;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class TimeStampUtil {
    //请求头标识
    public static final String TIME_STAMP_HEADER = "timestamp";

    //允许和服务器时间相差值，单位秒
    private final static int seconds = 300;

    /**
     * 判断时间某个时间戳和当前系统时间是否相差 seconds 秒
     *
     * @param timestamp
     * @return
     */
    public static boolean checkTimestamp(String timestamp) {
        try {
            if (StringUtils.isBlank(timestamp)) {
                return false;
            }
            long xc = (System.currentTimeMillis() - Long.parseLong(timestamp)) / 1000;
            if (xc < 0) {
                return false;
            }
            return xc <= seconds;
        } catch (Exception ex) {
            return false;
        }
    }


    /**
     * 获得时间戳字段
     *
     * @param request
     * @return
     */
    public static String getTimestampByRequest(HttpServletRequest request) {
        // 如果是get请求时timestamp从参数中获取
        //优先去请求头中获取sign值
        String headerTimestamp = request.getHeader(TIME_STAMP_HEADER);
        if (StringUtils.isBlank(headerTimestamp)) {
            return request.getParameter(TIME_STAMP_HEADER);
        } else {
            return headerTimestamp;
        }
    }

}
